<script setup lang="ts">
import { login, sendSMS } from "@/utils/api";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

// #ifdef MP-WEIXIN
// 获取 code 登录凭证
let code = "";
onLoad(async () => {
  const res = await wx.login();
  code = res.code;
});

// 获取用户手机号码
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  await checkedAgreePrivacy();
  const { encryptedData, iv } = ev.detail;
  const res = await postLoginWxMinAPI({ code, encryptedData, iv });
  loginSuccess(res.result);
};
// #endif

// 模拟手机号码快捷登录（开发练习）
// const onGetphonenumberSimple = async () => {
//   await checkedAgreePrivacy()
//   const res = await postLoginWxMinSimpleAPI('13123456789')
//   loginSuccess(res.result)
// }
const onGetphonenumberSimple = async () => {
        let params = {
    username: 'admin',
    password: '123321',
    grant_type: 'password',
  }
  login(params).then((res) => {

    uni.setStorageSync('token_type', res.data.token_type)
    uni.setStorageSync('token', res.data.access_token)
    goHome()
  })
}
const goHome = () => {
  uni.switchTab({
    url: '/pages/index/index',
  })
}
const loginSuccess = () => {
  // 成功提示
  uni.showToast({ icon: "success", title: "登录成功" });
  getMemberInfo();
};

// #ifdef H5
// 传统表单登录，测试账号：13123456789 密码：123456，测试账号仅开发学习使用。
const form = ref({
  account: "13123456789",
  password: "",
});
const mobileFocus = ref(false);

// 表单提交
const onSubmit = async () => {
  await checkedAgreePrivacy();
  const res = await postLoginAPI(form.value);
  loginSuccess(res.result);
};
// #endif

// 请先阅读并勾选协议
const isAgreePrivacy = ref(false);
const isAgreePrivacyShakeY = ref(false);
const checkedAgreePrivacy = async () => {
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: "none",
      title: "请先阅读并勾选协议",
    });
    // 震动提示
    isAgreePrivacyShakeY.value = true;
    setTimeout(() => {
      isAgreePrivacyShakeY.value = false;
    }, 500);
    // 返回错误
    return Promise.reject(new Error("请先阅读并勾选协议"));
  }
};

const onOpenPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  // 跳转至隐私协议页面
  wx.openPrivacyContract({});
  // #endif
};
const rules = {
  mobile: {
    type: "string",
    required: true,
    message: "请输入手机号码",
    trigger: ["blur"],
  },
  password: {
    type: "string",
    required: true,
    message: "请输入",
    trigger: ["blur"],
  },
  verifyCode: {
    type: "string",
    required: true,
    message: "请输入验证码",
    trigger: ["blur"],
  },
};
const uForm = ref();
const activeTab = ref(0);
const tips = ref("获取验证码");
const uCodeRef = ref(null);
const mobileRef = ref(null);
// 表单数据
const formData = reactive({
  mobile: "18170078211",
  verifyCode: "",
});
// 登录
const submit = () => {
  uForm.value.validate().then(async (res) => {
    await checkedAgreePrivacy();

    login({
      mobile: formData.mobile,
      verifyCode: formData.verifyCode,
      grant_type: "sms_code",
    }).then((res) => {
      loginSuccess(res.data);
    });
  });
};

const handleTapAgreePrivacy = () => {
  isAgreePrivacy.value = true;
};

const codeChange = (text) => {
  tips.value = text;
};

// 获取验证码
const getCode = async () => {
  if (formData.mobile && /^1\d{10}$/.test(formData.mobile)) {
    if (uCodeRef.value.canGetCode) {
      uni.showLoading({
        title: "正在获取验证码",
      });
      try {
        let params = {
          mobile: formData.mobile,
          type: 2,
        };
        console.log(formData.mobile);
        const { data } = await sendSMS(params);
        uni.hideLoading();
        uni.$u.toast("验证码已发送");
        // 通知验证码组件内部开始倒计时
        uCodeRef.value.start();
      } catch (e) {
        console.error(e);
      }
    } else {
      mobileFocus.value = false;
      uni.$u.toast("倒计时结束后再发送");
    }
  } else {
    uni.$u.toast("请输入正确的手机号码");
    mobileFocus.value = true;
  }
};
</script>

<template>
  <view class="viewport">
    <view class="logo">
      <image src="@/static/img/loginlogo.png"></image>
    </view>

    <view class="login">
      <!-- 表单登录 -->
      <u--form :model="formData" :rules="rules" ref="uForm" labelWidth="100">
        <u-form-item label="+86" prop="mobile" :borderBottom="true">
          <u--input
            border="none"
            clearable
            v-model="formData.mobile"
            :focus="mobileFocus"
            placeholder="请输入手机号码"
          />
        </u-form-item>
        <u-form-item
          v-if="activeTab == 0"
          label="验证码"
          prop="verifyCode"
          :borderBottom="true"
        >
          <u-input
            v-model="formData.verifyCode"
            placeholder="请输入验证码"
            border="none"
          />
          <template #right>
            <u-code
              ref="uCodeRef"
              @change="codeChange"
              seconds="60"
              changeText="X秒重新获取"
            ></u-code>
            <!-- <template #right> 获取验证码 </template> -->
            <text @tap="getCode" class="yanzm">{{ tips }}</text>
          </template>
        </u-form-item>
        <u-form-item v-else>
          <u-input
            v-model="formData.password"
            placeholder="请输入密码"
            password
            border="none"
          >
            <!-- <template slot="prefix">
              <view class="paddingicon">
                <image class="codeicon" src="~@/static/gaoshi/codeicon.png"></image>
              </view>
            </template> -->
          </u-input>
        </u-form-item>
      </u--form>
      <button  @tap="submit" class="button phone">
        注册
      </button>
      <!-- 小程序端授权登录 -->
      <!-- #ifdef MP-WEIXIN -->
      <view class="button-privacy-wrap" v-if="false">
        <button
          :hidden="isAgreePrivacy"
          class="button-opacity button phone"
          @tap="checkedAgreePrivacy"
        >
          请先阅读并勾选协议
        </button>
        <view class="iphone">139****9315</view>
        <button
          class="button phone"
          open-type="getPhoneNumber"
          @getphonenumber="onGetphonenumber"
        >
          <text class="icon icon-phone"></text>
          本机号码一键登录
        </button>
      </view>
      <!-- #endif -->
      <view class="extra">
        <view class="caption">
          <text>其他号码登录</text>
        </view>
        <view class="options">
          <!-- 通用模拟登录 -->
          <button @tap="onGetphonenumberSimple">
            <text class="icon icon-phone">模拟快捷登录</text>
          </button>
        </view>
      </view>
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @tap="handleTapAgreePrivacy">
          <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
          <text>登录即同意</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal"
          >《用户协议》</navigator
        >
        和
        <text class="link" @tap="onOpenPrivacyContract">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>
<style>
page {
  height: 100%;
  color: #060c3c;
  background: #FFFFFF;
}
  </style>

<style lang="scss" scoped>


.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
  background:  url('http://192.168.0.37:9000/zgyp/20231226/2c035f82a9e14e188760eb13143605d8.png') no-repeat;
  background-size: 100% 650rpx;
  /* background: linear-gradient(180deg, #ff8952 0%, rgba(255, 201, 175, 0) 100%)
    no-repeat;
  background-size: auto 516rpx; */
}

.logo {
  text-align: center;
  height: 500rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  image {
    width: 355rpx;
    height: 179rpx;
  }
}

.login {
  display: flex;
  flex-direction: column;

  flex: 1;
  padding: 40rpx 20rpx 20rpx;

  .input {
    width: 100%;
    height: 120rpx;
    font-size: 28rpx;
    /* border-bottom: 1px solid #ddd; */
    padding-left: 30rpx;
    /* margin-bottom: 20rpx; */
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 90rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;

    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phoneactive {
    background: #953B82;
    border-radius: 8rpx;
    margin-top: 111rpx;
  }
  .phone {
    background: #953B82;
    border-radius: 8rpx;
    /* opacity: 0.5; */
    color: #fff;
    margin-top: 111rpx;
  }

  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 50rpx 70rpx 0;

    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #060c3c;
      position: relative;

      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;

      button {
        padding: 0;
        background-color: transparent;

        &::after {
          border: none;
        }
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }

    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

@keyframes animate__shakeY {
  0% {
    transform: translate(0, 0);
  }

  50% {
    transform: translate(0, -5rpx);
  }

  100% {
    transform: translate(0, 0);
  }
}

.animate__shakeY {
  animation: animate__shakeY 0.2s ease-in-out 3;
}

.button-privacy-wrap {
  position: relative;

  .button-opacity {
    opacity: 0;
    position: absolute;
    z-index: 1;
  }
}

.tips {
  position: absolute;
  bottom: 40rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #060c3c;
  text-align: center;

  .radio {
    transform: scale(0.6);
    margin-right: -4rpx;
    margin-top: -4rpx;
    vertical-align: middle;
  }

  .link {
    display: inline;
    color: #060c3c;
  }
}

.iphone {
  font-size: 44rpx;
  margin-bottom: 60rpx;
  margin-top: 10vh;
  text-align: center;
}

.loginline {
  border-bottom: 1px solid #ddd;
}

.label {
  width: 132rpx;
}
</style>
